using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;
namespace CGF
{
    public partial class PanelNotice : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private class CellInfo
        {
            public bool isMain, isEmpay;
            public int type, num;
            public string title, time, content, contentHeader;
        }
        private List<CellInfo> infos = new List<CellInfo>();
        private List<string[]> devicesMsgs = new List<string[]>();
        private JsonData notices;
        private int myTotalDeviceCount;
        private int currOpenedType;

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelNotice>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelNotice>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelNotice", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(Close);

            ScrollView.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                CellInfo info = infos[index];
                if (!info.isMain && info.isEmpay)
                {
                    cell.gameObject.Get<GameObject>("MainBg").SetActive(false);
                    cell.gameObject.Get<GameObject>("SubBg").SetActive(true);
                    cell.gameObject.Get<GameObject>("Title").SetActive(false);
                    cell.gameObject.Get<GameObject>("Time").SetActive(false);
                    cell.gameObject.Get<GameObject>("Content").SetActive(false);
                    cell.gameObject.Get<GameObject>("Empty").SetActive(true);
                    cell.gameObject.Get<Text>("Empty").text = I18N_empty_tip;
                }
                else
                {
                    cell.gameObject.Get<GameObject>("Empty").SetActive(false);
                    cell.gameObject.Get<GameObject>("MainBg").SetActive(info.isMain);
                    cell.gameObject.Get<GameObject>("SubBg").SetActive(!info.isMain);
                    cell.gameObject.Get<GameObject>("Title").SetActive(true);
                    cell.gameObject.Get<GameObject>("Time").SetActive(!info.isMain);
                    cell.gameObject.Get<GameObject>("Content").SetActive(true);
                    cell.gameObject.Get<Text>("TextBadge").text = info.num.ToString();
                    Text title = cell.gameObject.Get<Text>("Title");
                    title.text = info.title;
                    Vector2 pos = title.rectTransform.anchoredPosition;
                    pos.y = info.isMain ? 0 : 23;
                    title.rectTransform.anchoredPosition = pos;
                    cell.gameObject.Get<Text>("Time").text = info.time;
                    cell.gameObject.Get<Text>("Content").text = info.contentHeader;

                    if (info.isMain)
                    {
                        title.text += $" ({info.num})";
                        string spriteName;
                        if (info.type == 0)
                        {
                            spriteName = "icon_laba";
                        }
                        else if (info.type == 1)
                        {
                            spriteName = "icon_jiqi";
                        }
                        else
                        {
                            spriteName = "icon_pay";
                        }
                        cell.gameObject.Get<Image>("Icon").sprite = gameObject.Get<Sprite>(spriteName);
                        float x = -200;
                        RectTransform titleTrans = cell.gameObject.Get<RectTransform>("Title");
                        titleTrans.anchoredPosition = new Vector2(x, titleTrans.anchoredPosition.y);
                        RectTransform contentTrans = cell.gameObject.Get<RectTransform>("Content");
                        contentTrans.anchoredPosition = new Vector2(x, contentTrans.anchoredPosition.y);
                    }
                    else
                    {
                        float x = -300;
                        RectTransform titleTrans = cell.gameObject.Get<RectTransform>("Title");
                        titleTrans.anchoredPosition = new Vector2(x, titleTrans.anchoredPosition.y);
                        RectTransform contentTrans = cell.gameObject.Get<RectTransform>("Content");
                        contentTrans.anchoredPosition = new Vector2(x, contentTrans.anchoredPosition.y);
                    }

                    CButton btn = cell.GetComponent<CButton>();
                    btn.triggerInterval = 0;
                    btn.SetClick(async () =>
                    {
                        if (info.isMain)
                        {
                            if (info.type == 0)
                            {
                                if (currOpenedType != 1)
                                {
                                    currOpenedType = 1;
                                }
                                else
                                {
                                    currOpenedType = 0;
                                }
                            }
                            else if (info.type == 1)
                            {
                                if (currOpenedType != 2)
                                {
                                    currOpenedType = 2;
                                }
                                else
                                {
                                    currOpenedType = 0;
                                }
                            }
                            RefreshCells();
                        }
                        else
                        {
                            string content = $"\n<size=30>{info.title}</size>\n{info.time}\n\n{info.content}\n\n";
                            string panelTitle = currOpenedType == 1 ? I18N_system_msg : I18N_device_msg;
                            PanelTextDetail.Open(panelTitle, content);
                        }
                    });
                }
            });

            ReqData();
        }

        private async void ReqData()
        {
            //系统消息
            var res = await Network.Get("/v1/user/notice");
            notices = res.jsonData["data"]["notices"];
            //我的设备租赁记录
            res = await Network.Get("/v1/order?limit=10000");
            myTotalDeviceCount = (int)res.jsonData["data"]["totalCount"];
            devicesMsgs.Clear();
            JsonData list = res.jsonData["data"]["orders"];
            for (int i = 0; i < list.Count; i++)
            {
                JsonData data = list[i];
                JsonData deviceData = GlobalData.GetDeviceByShopId((int)data["shop_id"]);
                string type = (int)data["type"] == 0 ? I18N_buy : I18N_renew;
                string num = data["num"].ToString();
                string name = Utils.GetI18N(deviceData["name"].ToString());
                string preIncome = StringHelper.SurportSpace(Utils.GetI18N(deviceData["subtitle"].ToString())); //预估收益
                devicesMsgs.Add(new []
                {
                    name,
                    I18N_device_content.Replace("{type}", type).Replace("{num}", num).Replace("{name}", name).Replace("{amount}", preIncome),
                    TimeHelper.Parse2Date(data["created_at"].ToString(), false)
                });
            }
            //构建列表
            RefreshCells();
        }

        private void RefreshCells()
        {
            int maxContentLength = 40;
            infos.Clear();
            infos.Add(new CellInfo()
            {
                isMain = true,
                type = 0,
                title = I18N_system_msg,
                num = notices.Count,
            });
            if (currOpenedType == 1)
            {
                for (int i = 0; i < notices.Count; i++)
                {
                    JsonData notice = notices[i];
                    string content = Utils.GetI18N(notice["content"].ToString());
                    infos.Add(new CellInfo()
                    {
                        isMain = false,
                        title = Utils.GetI18N(notice["title"].ToString()),
                        content = content,
                        contentHeader = content.Length > maxContentLength ? content.Substring(0, maxContentLength) + "..." : content,
                        time = TimeHelper.Parse2Date(notice["created_at"].ToString(), false),
                    });
                }
                if (notices.Count == 0)
                {
                    infos.Add(new CellInfo()
                    {
                        isMain = false,
                        isEmpay = true,
                    });
                }
            }
            infos.Add(new CellInfo()
            {
                isMain = true,
                type = 1,
                title = I18N_device_msg,
                num = myTotalDeviceCount,
            });
            if (currOpenedType == 2)
            {
                for (int i = 0; i < devicesMsgs.Count; i++)
                {
                    string[] msg = devicesMsgs[i];
                    string content = Utils.GetI18N(msg[1]);
                    Debug.LogError($">>>>>>>{content}");
                    infos.Add(new CellInfo()
                    {
                        isMain = false,
                        title = Utils.GetI18N(msg[0]),
                        content = content,
                        contentHeader = content.Length > maxContentLength ? content.Substring(0, maxContentLength) + "..." : content,
                        time = msg[2],
                    });
                }
                if (devicesMsgs.Count == 0)
                {
                    infos.Add(new CellInfo()
                    {
                        isMain = false,
                        isEmpay = true,
                    });
                }
            }
            ScrollView.SetTotalNumber(infos.Count);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
